import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Select, Card, Space, Table, Tag, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import {
  reqGetHospitalList,
  reqGetPorvince,
  reqGetDit,
  reqGetLine,
} from '@api/hospitalList';
import {
  IhospitalList,
  IhospitalListItem,
  IprovinceList,
  IDitList,
} from '@api/hospitalList/model/hospitalListType';
import { Navigate } from 'react-router-dom';
const { Option } = Select;



let flag = false
export default function Index() {
  const [list, setList] = useState<IhospitalList>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(2);
  const [total, setTotal] = useState(0);

  //省、市、区的状态
  const [province, setProvince] = useState<IprovinceList>([]);
  const [city, setCity] = useState<IDitList>([]);
  const [dis, setDis] = useState<IDitList>([]);
  const [hosType, setHosType] = useState<IDitList>([]);

  //form实例，然后与form标签绑定
  const [form] = Form.useForm();

  //路径导航
  const navigate =useNavigate()
  // //挂载是发请求获取数据
  useEffect(() => {
    getHospitalList(1, 2);
    getProvice();
    //医院类型在挂载阶段执行
    getType();
  }, []);
  //获取数据列表
  const getHospitalList = async (page: number, limit: number) => {
    const param = form.getFieldsValue()
    //判断点击查询按钮才执行
    let result
    if(flag) {
       result = await reqGetHospitalList({ page, limit ,...param });
    }else{
       result = await reqGetHospitalList({ page, limit });
    }
    setList(result.content);
    setTotal(result.totalElements);
  };
  //在挂载的时候获取省数据
  const getProvice = async () => {
    const result = await reqGetPorvince();
    setProvince(result);
  };

  //获取市数据
  const getCity = async (code: string) => {
    const result = await reqGetDit(code);
    setCity(result);
  };
  //获取区数据
  const getDis = async (code: string) => {
    const result = await reqGetDit(code);
    setDis(result);
  };
  //获取医院类型数据
  const getType = async () => {
    const result = await reqGetDit();
    setHosType(result);
  };

  //点击查询触发
  const onFinish = (values: any) => {
    flag=true
    getHospitalList(1,pageSize)
    setPage(1) 
  };
  const clearFin=() =>{
    flag=false
    form.resetFields()
    getHospitalList(1,pageSize)
    setPage(1) 
    
  }


  const columns: ColumnsType<IhospitalListItem> = [
    {
      title: '序号',
      render: (_, record, index) => index + 1,
      align: 'center',
      width: 80,
    },
    {
      title: '医院logo',
      render(_) {
        // 注意: 服务器响应回来的base64字符串没有前缀,所以我们需要额外添加
        return (
          <img src={'data:image/png;base64,' + _.logoData} alt="" width="80" />
        );
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(_) {
        return _.param.hostypeString;
      },
    },
    {
      title: '等级',
      render(_) {
        return _.param.fullAddress;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status ? '已上线' : '未上线';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render(_) {
        return (
          <Space>
            <Button type="primary" onClick={() =>{navigate(`/syt/hospital/hospitalList/show/${_.id}`)}}>查看</Button>
            <Button type="primary" onClick={() =>{navigate(`/syt/hospital/hospitalList/schedule/${_.hoscode}`)}}>排班</Button>
            <Button type="primary" onClick={
              async() =>{
                //发送请求
               await reqGetLine(_.id ,_.status ? 0: 1)
               message.success('状态修改成功')
               //页面数据重新渲染
               getHospitalList(page,pageSize)

              }
            }>{_.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
      width: 120,
    },
  ];
  return (
    <Card>
      <Form
        layout="inline"
        name="basic"
        onFinish={onFinish}
        autoComplete="off"
        form={form}
      >
        <Form.Item name="provinceCode">
          <Select
            style={{ width: 200, marginBottom: 20 }}
            placeholder="请选择省"
            //Form的onChange事件，监听数据变化
            onChange={(value) => {
              getCity(value);
            }}
          >
            {province.map((item) => (
              <Option key={item.id}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            style={{ width: 200, marginBottom: 20 }}
            placeholder="请选择市"
            onChange={(value) => {
              getDis(value);
            }}
          >
            {city.map((item) => (
              <Option key={item.id}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select style={{ width: 200 }} placeholder="请选择区">
            {dis.map((item) => (
              <Option key={item.id}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编码" />
        </Form.Item>
        <Form.Item name="hostype">
          <Select
            style={{ width: 200, marginBottom: 20 }}
            placeholder="医院类型"
          >
            {hosType.map((item) => (
              <Option key={item.id}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            style={{ width: 200, marginBottom: 20 }}
            placeholder="医院状态"
          >
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={clearFin}>清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={list}
        rowKey={'id'}
        pagination={{
          current: page,
          total,
          pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [2, 5, 10],
          showTotal: (total) => `共${total}条`,

          onChange(page, pageSize) {
            setPage(page);
            setPageSize(pageSize);
            getHospitalList(page, pageSize);
          },
        }}
      />
    </Card>
  );
}
